package auth

import (
	"context"
	"github.com/go-kratos/kratos/v2/log"
	"github.com/go-kratos/kratos/v2/middleware"
	"go-kratos-demo/internal/lib/consts"
	"go-kratos-demo/internal/lib/contextx"
)

func ParseToken(logger log.Logger) middleware.Middleware {

	return func(handler middleware.Handler) middleware.Handler {

		return func(ctx context.Context, req interface{}) (reply interface{}, err error) {

			// 获取请求头
			header := contextx.NewHeader(ctx)

			userToken := header.GetToken()
			if userToken == "" {
				return handler(ctx, req)
			}
			ctx = context.WithValue(ctx, contextx.HeaderTokenKey, userToken)

			// 解析Token
			rExtUserId, err := "", nil
			if err != nil {
				// 记录日志
				return handler(ctx, req)
			}

			// 附加数据
			if rExtUserId != "" {
				ctx = context.WithValue(ctx, consts.CtxUserIdKey, rExtUserId)
			}

			return handler(ctx, req)

		}
	}
}
